import pygtk
pygtk.require('2.0')
import gtk
import os, sys, string, glob

from yadict.gui.modaldialog import ModalDialog
from yadict.util.sqlutil import openDatabase,closeDatabase
from yadict.util.ioutil import buildDatabaseNoPatch

class DatabasePage(gtk.VBox):

    def changeCompletion(self, widget):
        # value should be gt 0 and lt 21
        try:
            limit = int(widget.get_text())
            
            if limit < 1 or limit > 20:
                modal = ModalDialog("No valid limit")
                widget.set_text("5")
                return
                
            self.yadictData.limitCompletion = limit
        except:
            modal = ModalDialog("Check limit")
            widget.set_text("5")
            return
            
    def build(self, widget):
        sourcePath = self.entrySource.get_text()
        dbName = self.entryDbName.get_text()
        
        if sourcePath == None or sourcePath.strip() == "":
            modal = ModalDialog("No source")
            return
        if dbName == None or dbName.strip() == "":
            modal = ModalDialog("No dbname")
            return

        # check extension .db
        splitDbName = os.path.splitext(dbName)
        if splitDbName == None or len(splitDbName) != 2 or splitDbName[1] != '.db':
            modal = ModalDialog("No .db extension")
            return
        
        # check source
        if os.path.exists(sourcePath) == False:
            modal = ModalDialog("No source path")
            return
        
        # build db
        ret = buildDatabaseNoPatch(sourcePath, self.yadictData.repositoryDatabase + "/" + dbName)
        if ret != None:
            modal = ModalDialog(str(ret) + " records loaded")
            return
        else:
            modal = ModalDialog("No database created")
            return

    def refreshDatabase(self, widget):
        self.refreshComboDb()

    def loadDatabase(self, widget):
        # load current database
        if self.comboBoxLoadDb.get_active_text() != None:
            if self.yadictData.connection != None:
                closeDatabase(self.yadictData.connection)

            connection = openDatabase(self.yadictData.repositoryDatabase + "/" + self.comboBoxLoadDb.get_active_text())
            self.yadictData.setConnection(connection, self.comboBoxLoadDb.get_active_text())
            self.labelLoadedDbDyn.set_text(self.yadictData.currentDatabaseName)
            
            if self.yadictData.connection == None:
                modal = ModalDialog("No database loaded")
            else:
                modal = ModalDialog("Database loaded")
        else:
            modal = ModalDialog("No database selected")
        
    def refreshComboDb(self):
        
        pathDatabase = self.yadictData.repositoryDatabase + '/*.db'
        databases = glob.glob(pathDatabase)
        
        # clean combo
        
        for x in range(0, self.countDatabase):
            self.comboBoxLoadDb.remove_text(0)
        
        self.countDatabase = len(databases)
        
        for database in databases:
            print "load database " + database
            self.comboBoxLoadDb.append_text(os.path.basename(database))
            
    def buildLayout(self):

        # begin open database
        frameLoadDatabase = gtk.Frame()
        frameLoadDatabase.set_label("Load Database ")
        frameLoadDatabase.set_label_align(0,0.5)
        frameLoadDatabase.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
        frameLoadDatabase.set_border_width(1)
        
        vLoadBox = gtk.VBox(False,5)
        vLoadBox.show()
        
        hLoadBox = gtk.HBox(False,5)
        hLoadBox.show()

        labelLoadDb = gtk.Label("Load:")
        labelLoadDb.show()

        self.comboBoxLoadDb = gtk.combo_box_new_text()
        self.comboBoxLoadDb.show()
        
        self.refreshComboDb()
        
        btLoadDb = gtk.Button("Load")
        btLoadDb.connect("clicked", self.loadDatabase)
        btLoadDb.show()
        
        btRefreshDb = gtk.Button("Refresh")
        btRefreshDb.connect("clicked", self.refreshDatabase)
        btRefreshDb.show()
        
        hLoadBox.pack_start(labelLoadDb, False, False, 5)
        hLoadBox.pack_start(self.comboBoxLoadDb, True, True, 5)
        hLoadBox.pack_start(btLoadDb, False, False, 5)
        hLoadBox.pack_start(btRefreshDb, False, False, 5)
        
        hLoadBox2 = gtk.HBox(False,5)
        hLoadBox2.show()

        labelLoadedDb = gtk.Label("Database loaded:")
        labelLoadedDb.show()
        
        self.labelLoadedDbDyn = gtk.Label(self.yadictData.currentDatabaseName)
        self.labelLoadedDbDyn.show()
        
        hLoadBox2.pack_start(labelLoadedDb, False, False, 5)
        hLoadBox2.pack_start(self.labelLoadedDbDyn, False, False, 5)
        
        vLoadBox.pack_start(hLoadBox, False, False, 10)
        vLoadBox.pack_start(hLoadBox2, False, False, 10)
        
        frameLoadDatabase.add(vLoadBox)
        frameLoadDatabase.show()
        
        # end open database
        
        # begin build database
        frameBuildDatabase = gtk.Frame()
        frameBuildDatabase.set_label("Build Database ")
        frameBuildDatabase.set_label_align(0,0.5)
        frameBuildDatabase.set_shadow_type(gtk.SHADOW_ETCHED_OUT)
        frameBuildDatabase.set_border_width(1)
        
        vBuildBox = gtk.VBox(False,5)
        vBuildBox.show()
        
        hBuildBox1 = gtk.HBox(False,5)
        hBuildBox1.show()
        
        labelSource = gtk.Label("Source ")
        labelSource.show()
        
        self.entrySource = gtk.Entry()
        self.entrySource.show()
        
        hBuildBox1.pack_start(labelSource, False, False, 5)
        hBuildBox1.pack_start(self.entrySource, True, True, 5)
        
        hBuildBox2 = gtk.HBox(False,5)
        hBuildBox2.show()
        
        labelDbName = gtk.Label("DB Name ")
        labelDbName.show()
        
        self.entryDbName = gtk.Entry()
        self.entryDbName.show()
        
        btClean = gtk.Button("Build")
        btClean.connect("clicked", self.build)
        btClean.show()
        
        hBuildBox2.pack_start(labelDbName, False, False, 5)
        hBuildBox2.pack_start(self.entryDbName, True, True, 5)
        hBuildBox2.pack_start(btClean, False, False, 5)
        
        vBuildBox.pack_start(hBuildBox1, False, False, 10)
        vBuildBox.pack_start(hBuildBox2, False, False, 10)
       
        frameBuildDatabase.add(vBuildBox)
        frameBuildDatabase.show()
        
        # end build database
        
        # begin limit
        hLimitCompletionBox = gtk.HBox(False,5)
        hLimitCompletionBox.show()

        labelLimitCompletion = gtk.Label("Limit Completion (1-20):")
        labelLimitCompletion.show()
        
        entryLimitCompletion = gtk.Entry()
        entryLimitCompletion.set_text(str(self.yadictData.limitCompletion))
        entryLimitCompletion.show()
        entryLimitCompletion.connect("changed", self.changeCompletion)
        
        hLimitCompletionBox.pack_start(labelLimitCompletion, False, False, 5)
        hLimitCompletionBox.pack_start(entryLimitCompletion, True, True, 5)
        
        # end limit
        
        self.pack_start(frameLoadDatabase, False, False, 10)
        self.pack_start(frameBuildDatabase, False, False, 10)
        self.pack_start(hLimitCompletionBox, False, False, 10)

    def __init__(self, yadictData):
        
        # something like super() in java
        gtk.VBox.__init__(self, False, 5)
        self.countDatabase = 0
        self.yadictData = yadictData
        self.buildLayout()
        
        # show me
        self.show()